<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { ElUpload, ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
// import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
import { createImageViewer } from '@/components/ImageViewer'

import { ref, computed } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { pick } from 'lodash-es'
import { getQRCodeApi, saveQRCodeApi } from '@/api/qrcode'
import { uploadFile } from '@/api/upload'

// Search

// Table
const columns: TableColumn[] = [
  {
    field: 'title',
    label: '标题'
  },
  {
    field: 'imageUrl',
    label: '二维码',
    showOverflowTooltip: false,
    slots: {
      default: ({ row }) =>
        row.imageUrl ? (
          <img
            class="w-[50px] cursor-pointer"
            src={row.imageUrl}
            onClick={() => onImageView([row.imageUrl])}
          />
        ) : null
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 120,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return (
          <div class="flex justify-center items-center">
            <BaseButton type="primary" size="small" onClick={() => onOpenDialog(row)}>
              {{
                icon: () => <Icon size={20} icon="carbon:edit" />,
                default: () => '编辑'
              }}
            </BaseButton>
          </div>
        )
      }
    }
  }
]

const { tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { data, count } = await getQRCodeApi({})
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList } = tableState
const { getList } = tableMethods

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const title = computed(() => (isEdit.value ? '编辑' : '新增'))

// Form
const { formRegister, formMethods } = useForm()
const { getElFormExpose, setValues, getFormData } = formMethods

const { required } = useValidator()

const uploadImage = ref(false)

const schema = computed<FormSchema[]>(() => [
  {
    field: 'title',
    label: '标题',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'imageUrl',
    label: '二维码',
    formItemProps: {
      slots: {
        default: (formData) => {
          const httpRequest = async (options) => {
            uploadImage.value = true
            const formDataTemp = new FormData()
            formDataTemp.append('file', options.file)
            const { data } = await uploadFile(formDataTemp)
            formData.imageUrl = data[0].fileUrl
            uploadImage.value = false
          }

          const onRemoveFile = () => {
            formData.imageUrl = ''
          }
          return formData.imageUrl ? (
            <div class="w-[200px] h-[200px] overflow-hidden relative border-[1px] border-dashed border-[#ccc] border-rd-[6px]">
              <img class="w-[100%] absolute top-[50%] translate-y-[-50%]" src={formData.imageUrl} />
              <div
                class="w-[100%] h-[100%] absolute top-0 left-0 inline-flex justify-center items-center bg-[#000] opacity-1 hover-opacity-[0.5]"
                onClick={onRemoveFile}
              >
                <Icon
                  class="!color-[#fff] cursor-pointer"
                  icon="material-symbols:delete-outline"
                  size={30}
                />
              </div>
            </div>
          ) : (
            <ElUpload
              action="#"
              limit={1}
              accept="image/*"
              autoUpload={true}
              showFileList={false}
              disabled={uploadImage.value}
              httpRequest={httpRequest}
              beforeUpload={beforeUpload}
            >
              {{
                default: () => (
                  <Icon
                    icon={uploadImage.value ? 'line-md:uploading-loop' : 'mingcute:add-fill'}
                    size={40}
                  />
                ),
                tip: () => <div class="color-[#f59e0b]">文件大小不能超过20M</div>
              }}
            </ElUpload>
          )
        }
      },
      rules: [required('请上传二维码')]
    }
  }
])

// 上传前校验文件
const beforeUpload = (rawFile) => {
  if (rawFile.size > 20 * 1024 * 1024) {
    ElMessage.error('图片过大,请重新选择!')
    return false
  }
  return true
}

// 图片预览
const onImageView = (urlList) => {
  createImageViewer({ urlList })
}

// 打开弹窗
const onOpenDialog = (row) => {
  visible.value = true
  // 编辑
  isEdit.value = true
  setValues(pick(row, ['id', 'title', 'imageUrl']))
}

// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}

const disabled = ref(false)
// 立即提交
const onFormSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate(async (isValid) => {
    if (!isValid) {
      ElMessage.warning('请填写完整信息')
      return
    } else {
      disabled.value = true
      const formData = await getFormData()
      saveQRCodeApi({ ...formData })
        .then(() => {
          visible.value = false
          ElMessage.success('操作成功！')
          getList()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          disabled.value = false
        })
    }
  })
}
</script>

<template>
  <ContentWrap title="二维码管理">
    <Table :columns="columns" :data="dataList" :loading="loading" />
    <!-- 添加客服二维码-弹窗 -->
    <Dialog v-model="visible" :title="title">
      <Form
        class="w-[400px] ml-[auto] mr-[auto]"
        v-loading="disabled"
        :schema="schema"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton v-if="!isEdit" @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabeld="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
